<?php

function format_address(raw_address $raw_address)
{/*{{{*/
    $raw_address->set_status_init();

    $estate_name = $raw_address->estate_name;
    $house_address = $raw_address->house_address;
    $person_mobile_number = $raw_address->person_mobile_number;

    $last_same_raw_address = dao('raw_address')->find_last_formated_by_estate_name_and_house_address_and_person_mobile_number($estate_name, $house_address, $person_mobile_number);

    if ($last_same_raw_address->is_not_null()) {

        $raw_address->set_status_formated();
        $raw_address->snap_formated_address_string = $last_same_raw_address->snap_formated_address_string;

        return;
    }

    $estate = dao('estate')->find_by_name($estate_name);
    $output_address_slot = $estate->output_address_slot;

    if ($estate->is_null() || $output_address_slot->is_null()) {

        $raw_address->set_status_not_found();
        $raw_address->snap_formated_address_string = '';

        return;
    }

    $address_slots = dao('address_slot')->find_all_by_estate_order_by_number($estate);

    relationship_batch_load($address_slots, 'address_unit_turns.address_unit');

    $matched = false;

    foreach ($address_slots as $address_slot) {

        list($matched, $match_infos) = $address_slot->match_address($house_address);

        if ($matched) {

            if ($address_slot->is_contain_output_address_unit_yes()) {

                $raw_address->set_status_formated();
                $raw_address->snap_formated_address_string = $output_address_slot->get_formated_address_string($match_infos);
            } else {

                $raw_address->set_status_not_complete();
                $raw_address->snap_formated_address_string = '';
            }

            return;
        }
    }

    if (! $matched) {

        $raw_address->set_status_not_found();
        $raw_address->snap_formated_address_string = '';

        return;
    }
}/*}}}*/
